package com.mililoan.service.module.system.impl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.mililoan.model.system.Menu;
import com.mililoan.persist.system.MenuDao;
import com.mililoan.service.module.system.MenuBo;

@Service
public class MenuBoImpl implements MenuBo {
    private static Logger LOGGER	= LoggerFactory.getLogger(MenuBoImpl.class);
    
    @Autowired
    MenuDao menuDao;

    public Menu getMenu() {
        Map<Integer, Menu> menuMap = menuDao.getMenu();

        Menu menu = new Menu();
        for (Map.Entry<Integer, Menu> entry : menuMap.entrySet()) {
            Menu tempMenu = entry.getValue();
            if (tempMenu.getParentMenu() == 0) {
                menu.addMenu(tempMenu);
            } else {
                menuMap.get(tempMenu.getParentMenu()).addMenu(tempMenu);
            }
        }
        return menu;
    }

    public Menu getMenu(HashSet<Integer> actSet) {
        LOGGER.debug("初始化菜单开始");
        Map<Integer, Menu> menuMap = menuDao.getMenu();
        Menu menu = new Menu();
        for (Map.Entry<Integer, Menu> entry : menuMap.entrySet()) {
            Menu tempMenu = entry.getValue();
            // 判断是否有权限
            LOGGER.info("menuId"+String.valueOf(tempMenu.getMenuId()));
            Iterator<Integer> it = actSet.iterator();
            while(it.hasNext()){
            	int actId = it.next().intValue();
            	LOGGER.info("actId"+String.valueOf(actId));
            	if(actId==tempMenu.getMenuId()){
            		  if (tempMenu.getParentMenu() == 0) {
                          menu.addMenu(tempMenu);
                      } else {
                          menuMap.get(tempMenu.getParentMenu()).addMenu(tempMenu);
                      }
            	}
            }
            if (actSet.contains(tempMenu.getMenuId())) {
              
            }
        }
        LOGGER.debug("初始化菜单结束");
        return menu;
    }

    public List<Menu> getChildMenu(String menuUrl) {
        List<Menu> menuList = new ArrayList<Menu>();
        Map<Integer, Menu> menuMap = menuDao.getMenu();
        for (Map.Entry<Integer, Menu> entry : menuMap.entrySet()) {
            Menu tempMenu = entry.getValue();
            if (!StringUtils.isEmpty(tempMenu.getMenuUrl()) && menuUrl.indexOf(tempMenu.getMenuUrl()) >= 0) {
                for (Map.Entry<Integer, Menu> tmpMap : menuMap.entrySet()) {
                    if (tmpMap.getValue().getParentMenu() == tempMenu.getMenuId()) {
                        menuList.add(tmpMap.getValue());
                    }
                }
            }
        }
        return menuList;
    }
}
